<?php
/**
 * @since v1.0
 * @modify 2015.6.21
 * @copyright 深圳亿游
 */
require_once(LIB_PATH.'controller/root.con.php');

class teacherCon extends rootCon
{
    //老师管理端-》审核状态
    public function adminStatusAction()  {//the status of the school
        $uid = mylogin::getUid(true);
        $teacher = new Teacher();
        $find = $teacher->find(['uid'=>$uid]);
        $status = $teacher->status;
        if(!$find ){
            $status = 5;
        }

        $this->j(0,"",['status'=>$status]);
    }

    //老师管理端->添加机构
    public function savSchoolStatusAction(){
        $uid = mylogin::getUid(true);
        $teacher = new Teacher();
        $teacher->find(['uid'=>$uid]);
        $teacherId = $teacher->teacherId;

        $schoolId = r_int('schoolId');
        $teacherSchool = new SchoolTeacher();
        $teacherSchool->schoolId  = $schoolId;
        $teacherSchool->teacherId = $teacherId;
        $teacherSchool->find();
        if(s('status') && r('status')==STATUS_DELETE){
            $status = r_int('status');
        }else{
            $status = STATUS_SUBMIT;
        }
        $teacherSchool->status = $status;
        $teacherSchool->save();

        $this->j(0,"",['status'=>$status]);
    }

    //老师管理端->机构列表
    public function schoolListAction(){
        $uid = mylogin::getUid(true);
        $teacherUid = r_int('uid');

        if($uid != $teacherUid){
            $this->j(-3,'只能显示当前登录用户服务的机构列表');
        }

        $teacher = new Teacher();
        $teacher->find(['uid'=>$teacherUid]);
        $teacherId = $teacher->teacherId;

        $teacherSchool = new SchoolTeacher();
        $sql = "SELECT * FROM ".$teacherSchool->table()." WHERE teacherId=".$teacherId." AND status!=".STATUS_ADMIN_DELETE;

        if(r('isDebug')){
            $sql = "SELECT * FROM ".$teacherSchool->table()." WHERE teacherId=1";
        }

        $rect = $teacherSchool->pager($sql,20);
        $i = 0;
        foreach($rect['list'] as $item){
            $schoolId = $item['schoolId'];
            $school = new School();
            $school->find($schoolId);
            $school->hide();

            
            $courseObj = new Course();
            $sql = "SELECT COUNT(1) AS NUM FROM ".$courseObj->table()." WHERE status IN (0,3,4) AND schoolId=".$schoolId;
            $one = $courseObj->one($sql);
            $school->arr['courseCount'] = $one['NUM'];


            $rect['list'][$i]['schoolInfo'] = $school->arr;

            if($school->schoolName && $school->status!=STATUS_ADMIN_DELETE){
                $rect['list'][$i]['schoolInfo'] = $school->arr;
            }else{
                unset($rect['list'][$i]);
            }
            $i++;
        }

        $list = [];
        foreach($rect['list'] as $item){
            $list[]  = $item;
        }
        $rect['list'] = $list;

        $this->j(0,"",$rect);
    }

    //*老师主页端-》课程接口
    public function courseListAction(){
        $uid = mylogin::getUid(false);
        $teacherId = r_int('teacherId');
        if(!$teacherId) $this->j(-1,"缺少ID参数",['teacherId'=>$teacherId]);
        $courseTeacher = new CourseTeacher();
        $courseTeacher->teacherId = $teacherId;
        $courseTeacher->status = STATUS_PUBLISH;
        $con = $courseTeacher->getConByLoad();
        $sql = "SELECT * FROM ".$courseTeacher->table()." WHERE ".$con;
        $rect = $courseTeacher->pager($sql);
        $i = 0;
        $newList = [];
        foreach($rect['list'] as $item){
            $course = new Course();
            $course->courseId = $item['courseId'];
            $course->status = STATUS_PUBLISH;
            $find = $course->find();

            if(!$find){
                $rect['list'][$i] = null;
                unset($rect['list'][$i]);
                $i++;
                continue;
            }

            $rect['list'][$i]['courseName'] = $course->courseName;
            $rect['list'][$i]['uploadImg'] = $course->uploadImg;
            $rect['list'][$i]['oldPrice'] = $course->oldPrice;
            $rect['list'][$i]['price'] = $course->price;
            $rect['list'][$i]['totalClassHours'] = $course->totalClassHours;

            $courseImage = new CourseImage();
            $courseImage->courseId = $course->courseId;
            $courseImage->status = STATUS_PUBLISH;
            $all = $courseImage->findAll($courseImage->getConByLoad());

            $rect['list'][$i]['imageList'] = $all;
            $newList[] = $rect['list'][$i];
            $i++;
        }

        $rect['list'] = $newList;

        $this->j(0,'',$rect);
    }

    //*老师管理端->老师主页 累计值
    public function totalAction(){
        $uid = mylogin::getUid(true);
        $teacherId = r_int('teacherId');
        if(!$teacherId) $this->j(-1,"缺少ID参数",['teacherId'=>$teacherId]);

        $teacherObj = new Teacher();
        $teacherObj->find($teacherId);
        $teacherObj->hide();
        $rect = $teacherObj->arr;

        $courseMain = new CourseMain();
        $courseMain->find($teacherObj->courseMainId);
        $rect['courseMain'] = $courseMain->courseMain;

        //学过的人统计
        $teacherLearned = new TeacherLearned();
        $teacherLearned->teacherId = $teacherId;
        $sql = "SELECT COUNT(1) AS NUM FROM ".$teacherLearned->table()." WHERE ".$teacherLearned->getConByLoad();
        $one = $teacherLearned->one($sql);
        
        $rect['learned'] = $one['NUM'];
        if($teacherObj->learned != $one['NUM']){
            $teacherObj->learned = $one['NUM'];
            if($teacherObj->teacherId) $teacherObj->save();
        }

        $courseSub = new CourseSub();
        $courseSub->find($teacherObj->courseSub);
        $rect['courseSub'] = $courseSub->courseSub;



        $user = new User();
        $user->find($uid);
        $rect['mobile'] = $user->mobile;
        $rect['mobile'] = $user->mobile;

        $visitor = new Visitor();
        $sql = "SELECT COUNT(1) AS NUM FROM ".$visitor->table()." WHERE teacherId=".$teacherId;
        $one = $visitor->one($sql);
        $rect['renqizhi']    = intval($one['NUM']);
        $info = '';
        if(IS_DEBUG) $info = $sql;

        $rect['remarkCount'] = $this->getRemarkCount($teacherId);
        $rect['courseCount'] = $this->getCourseCount($teacherId);

        $this->j(0,$info,$rect);
    }

    private function getCourseCount($teacherId){
        $courseTeacher = new CourseTeacher();
        $sql = "SELECT COUNT(1) AS NUM FROM ".$courseTeacher->table()." WHERE teacherId=".$teacherId." AND status=".STATUS_PUBLISH;
        $one = $courseTeacher->one($sql);
        return intval($one['NUM']);
    }

    private function getRemarkCount($teacherId){
        $remarkTeacher = new RemarkTeacher();
        $sql = "SELECT COUNT(1) AS NUM FROM ".$remarkTeacher->table()." WHERE teacherId=".$teacherId." AND status=".STATUS_PUBLISH;
        $one = $remarkTeacher->one($sql);
        return intval($one['NUM']);
    }

    //*老师管理端->老师管理端
    public function statusAction(){
        $uid = mylogin::getUid(true);
        $teacher = new Teacher();
        $teacher->find(['uid'=>$uid]);
        $teacher->teacherId = intval($teacher->teacherId);

        $courseStr = $this->getCourseStr($teacher->teacherId);
        $trace = new Visitor();
        $today = date("Y-m-d");
        $sql = "SELECT uid FROM ".$trace->table()." WHERE courseId IN ($courseStr) AND created LIKE '$today%' GROUP BY uid ";
        $all = $trace->query($sql);
        $data['visitCount']  = count($all);
        

        $data['dateCount']   = Traceext::getDailyAppByTeacher($teacher->teacherId);//预约人数
        

        $teacherSchool = new SchoolTeacher();
        $sql = "SELECT COUNT(1) AS NUM FROM ".$teacherSchool->table()." WHERE status=".STATUS_PUBLISH." AND  teacherId=".$teacher->teacherId;
        $one = $teacherSchool->one($sql);
        $data['schoolCount'] = $one['NUM'];//在职机构数

        $teacherCourse = new CourseTeacher();
        $sql = "SELECT courseId FROM ".$teacherCourse->table()." WHERE status=".STATUS_PUBLISH." AND  teacherId=".intval($teacher->teacherId);        
        $allCourse = $teacherCourse->query($sql);
        $courseIds = [-1];
        foreach($allCourse as $item){
           if($item['courseId']) $courseIds[] = $item['courseId'];
        }
        $courseObj = new Course();
        $courseIdStr = join(',',$courseIds);
        $sql = "SELECT COUNT(1) AS NUM FROM ".$courseObj->table()." WHERE status=".STATUS_PUBLISH." AND  courseId IN ($courseIdStr)";        
        $one = $courseObj->one($sql);
        $data['courseCount'] = $one['NUM'];//在授课程数


        $order = new Order();
        $day = date('Y-m-d H:i:s',time()-24*3600*90);
        $sql = "SELECT COUNT(1) AS NUM FROM ".$order->table()." WHERE courseId IN (".$this->getCourseStr($teacher->teacherId).") AND status IN (1,2) AND created>'$day'";
        $one = $order->one($sql);
        $data['teachingCount'] = intval($one['NUM']);//在读学生

        $sql = "SELECT COUNT(1) AS NUM FROM ".$order->table()." WHERE  courseId IN (".$this->getCourseStr($teacher->teacherId).") AND status IN (1,2) ";
        $one = $order->one($sql);
        $data['studentCount']  = intval($teacher->learned + $one['NUM']);//累计学生

        $order = new Order();
        $sql = "SELECT SUM(buyerPay) AS TOTAL FROM ".$order->table()." WHERE teacherId=".$teacher->teacherId." AND orderType=".ORDER_TYPE_LIKE." AND status=".STATUS_BUYER_PAID;
        $one = $order->one($sql);
        $data['likeMoney'] = round($one['TOTAL'],2);//收到的赞赏
        $info = "";
        if(IS_DEBUG) $info = $sql;

        $data['likeCount'] = intval($teacher->likeCount);//获赞
        $data['wantCount'] = intval($teacher->want);//想学的人
        $data['teacherId'] = $teacher->teacherId;

        $this->j(0,"$info",$data);
    }

    private function getCourseStr($teacherId){
        $teacherCourse = new CourseTeacher();
        $teacherCourse->teacherId = $teacherId;
        $teacherCourse->status = STATUS_PUBLISH;
        $all = $teacherCourse->findAll();
        $i = 0;
        $courseIds = [-1];
        foreach($all as $item){
            if($item['courseId'])$courseIds[] = $item['courseId'];
            $i++;
        }
        $courseStr = join(",",$courseIds);
        return $courseStr;
    }

    //*老师管理端->我的
    public function mineAction(){
        $uid = mylogin::getUid(true);
        $user = new User();
        $user->find($uid);
        $rec = [];
        $rec['nick'] = $user->nick;
        $rec['avatar'] = $user->avatar;
        if(!preg_match("/^http/i",$rec['avatar'])){
            $rec['avatar']  = FRONT_URL.$rec['avatar'];
        }

        //我管理的老师
        $teacher = new Teacher();
        $teacher->find(['uid'=>$uid]);

        //学校数量
        $teacherSchool = new SchoolTeacher();
        $teacherSchool->teacherId = $teacher->teacherId;
        $teacherSchool->status = STATUS_PUBLISH;
        $all = $teacherSchool->findAll();
        $rec['schoolCount'] = count($all);

        $courseTeacher = new CourseTeacher();
        $courseTeacher->teacherId = $teacher->teacherId;
        $courseTeacher->status = STATUS_PUBLISH;
        $all = $teacherSchool->findAll();
        $rec['courseCount'] = count($all);
        $rec['teacherId']   = $teacher->teacherId;

        $this->j(0,"*老师管理端->我的",$rec);
    }

    //显示所有教师类别
    public function typeAction(){
        $teacherType = new TeacherType();
        $all = $teacherType->all('status='.STATUS_PUBLISH);
        $this->j(0,'',$all);
    }

    public function labelAction(){
        $uid = mylogin::getUid(true);
        $obj = new Label();
        $obj->load();
        $obj->status = STATUS_PUBLISH;

        $con = $obj->getConByLoad();
        $all = $obj->all($con);
        $rect['label'] = $all;

        $teacherType = new TeacherType();
        $all = $teacherType->all('status='.STATUS_PUBLISH);
        $rect['type'] = $all;

        $this->j(0,'教师类别',$rect);
    }

    public function getTeacherInfo($teacherId,$uid,$schoolId=0){
        $obj = new Teacher();
        $objId =  intval($teacherId);
        if(!$objId){
            $this->j(-2,'缺少参数',[$obj->key()=>$objId]);
        }

        $con = $obj->key()."=$objId AND (status=".STATUS_PUBLISH." OR uid=".$uid.")";
        $find = $obj->find($con);
        if(!$find){
            $this->j(-1,'没有找到对应的信息',[$obj->key()=>$objId]);
        }
        $obj->hide();
        if($obj->teacherYear){
            $obj->years = $obj->teacherYear;
        }


        $courseSub = new CourseSub();
        $courseSub->find($obj->courseSub);
        $obj->courseName = $courseSub->courseSub;

        $tmpObj = new TeacherEdu();
        $arr = $tmpObj->all("teacherId=".$objId,$tmpObj->key()." ASC");
        $obj->arr['teacherEdu'] = $arr;

        $tmpObj = new teacherJob();
        $arr = $tmpObj->all("teacherId=".$objId,$tmpObj->key()." ASC");
        $obj->arr['teacherJob'] = $arr;

        $tmpObj = new TeacherImage();
        $arr = $tmpObj->all("teacherId=".$objId." AND status=".STATUS_PUBLISH,$tmpObj->key()." ASC");
        $obj->arr['teacherImages'] = $arr;

        $tmpObj = new TeacherLabel();
        $arr = $tmpObj->all("teacherId=".$objId." AND status=".STATUS_PUBLISH,$tmpObj->key()." ASC");
        $i = 0;
        foreach($arr as $item){
            if(!preg_match("/^http/i",$item['labelImg'])){
                $arr[$i]['labelImg'] = FRONT_URL.$arr[$i]['labelImg'];
            }
            $i++;
        }
        $obj->arr['teacherLabel'] = $arr;

        $tmpObj = new CourseTeacher();
        $arr = $tmpObj->all("teacherId=".$objId."  AND status=".STATUS_PUBLISH, "sort ASC");
        $i = 0;
        $tmpArr = [];
        foreach($arr as $row){
            $courseId = $row['courseId'];
            $course = new Course();
            $course->find($courseId);
            $course->hide();
            if($course->status!=STATUS_ADMIN_DELETE && $course->status!=4){
                $tmpArr[] = $arr[$i];
                $tmpArr[count($tmpArr)-1]['courseInfo'] =  $course->arr;
            }
            //$arr[$i]['courseInfo'] = $course->arr;
            $i++;
        }

        $obj->arr['courseTeacher'] = $tmpArr;


        $school = new School();
        if($schoolId){
            $school->find($schoolId);
        }else if(!$obj->schoolId){
            $schoolTeacherObj = new SchoolTeacher();
            $schoolTeacherObj->teacherId = $teacherId;
            $schoolTeacherObj->find();
            $obj->schoolId = $schoolTeacherObj->schoolId;
            if($obj->schoolId && $obj->teacherId) $obj->save();
            $school->find($obj->schoolId);
        }else{
            $school->find($obj->schoolId);
        }

        $school->hide();
        $obj->arr['schoolName'] = $school->schoolName;
        $obj->arr['schoolInfo'] = $school->arr;
        $obj->arr['learned'] = $this->getTeacherLearned($objId);


        $bornYear = $obj->bornYear;
        if($bornYear){
            $bornYear = date("Y") - $bornYear;
            if($bornYear<0) $bornYear = "";
            $obj->arr['teacherAge'] = $bornYear;
        }else{
            $obj->arr['teacherAge'] = "未知";
        }

        $teacherLike = new TeacherLike();
        $teacherLike->teacherId = $teacherId;
        $teacherLike->uid = $uid;
        $find = $teacherLike->find();
        $obj->arr['iLike'] = $find;

        $teacherWant = new TeacherWant();
        $teacherWant->teacherId = $teacherId;
        $teacherWant->uid = $uid;
        $find = $teacherWant->find();
        $obj->arr['iWant'] = $find;

        return $obj->arr;
    }


    private function getTeacherLearned($teacherId){
        $c = new TeacherLearned();
        $all = $c->all(['teacherId',$teacherId]);
        $i =0;
        foreach($all as $item){
            if(!preg_match("/^http/i",$item['avatar'])){
                $all[$i]['avatar']  = FRONT_URL.$item['avatar'];
            }
            $i++;
        }
        return $all;
    }

    public function infoAction() {
        $uid = mylogin::getUid(true);
        $courseIdArr = r('courseId');
        if(is_array($courseIdArr)){//假设传入课程的数组courseId，则返回每个课程的sort排位第一的老师
            $list = [];
            $i = 0;
            foreach($courseIdArr as $courseId){
                if($i>6) break;
                $courseId = intval($courseId);
                //找到课程对应的老师
                $courseTeacher = new CourseTeacher();
                $sql = "SELECT ct.* FROM ".$courseTeacher->table()." ct LEFT JOIN tbl_teacher t ON ct.teacherId=t.teacherId WHERE ct.courseId=$courseId AND ct.status=3 AND t.status=3 ORDER BY sort ASC LIMIT 1";
                $t = $courseTeacher->one($sql);
                if($t){
                    $teacherId = $t['teacherId'];
                    $one = $this->getTeacherInfo($teacherId,$uid);
                    $list[] = $one;
                }else{
                    $list[] = false;//留空白
                }
                $i++;
            }
            $this->j(0,'列表',$list);
        }else{//单个老师
            $teacherId = r_int('teacherId');


            Traceext::addDailyVisitTeacher($teacherId);

            if(r('isAdmin')){
                $schoolId = r_int('schoolId');
                $teacher = $this->getTeacherInfo($teacherId,$uid,$schoolId);

                $schoolAdmin = new SchoolAdmin();
                $schoolAdmin->uid = $teacher['uid'];
                $schoolAdmin->schoolId = $schoolId;
                $find = $schoolAdmin->find();
                if($find){
                    $teacher['adminStatus'] = $schoolAdmin->status;
                }else{
                    $teacher['adminStatus'] = STATUS_SUBMIT;
                }

                $schoolTeacher = new SchoolTeacher();
                $schoolTeacher->schoolId  = $schoolId;
                $schoolTeacher->teacherId = $teacherId;
                $find = $schoolTeacher->find();
                if($find){
                    $teacher['schoolStatus'] = $schoolTeacher->status;
                    $teacher['schoolStatusInfo'] = "TA是您机构的老师";
                }else{
                    $teacher['schoolStatus']    = STATUS_SUBMIT;
                    $teacher['schoolStatusInfo'] = "还不是您机构的老师";
                }
            }else{
                $teacher = $this->getTeacherInfo($teacherId,$uid);
                
                if($teacher['schoolId']) {
                    $schoolAdmin = new SchoolAdmin();
                    $schoolAdmin->schoolId = $schoolId;
                    $schoolAdmin->uid = $uid;
                    $findAdmin = $schoolAdmin->find();
                    if(!$findAdmin) Traceext::log($uid,$teacher['teacherName'],$teacher['teacherName'],$teacher['schoolId'],$teacherId);
                }
            }

            $this->j(0,'详情',$teacher);
        }
    }

    public function saveAction() {
        $uid = mylogin::getUid(true);
        $obj = new Teacher();
        $teacherId = r_int($obj->key());
        $objId = $teacherId;
        if($objId){
            $find = $obj->find([[$obj->key(),$objId],['uid',$uid]]);
            if(!$find && !r('isAdmin')){
                $this->j(-1,'没有找到对应信息',[$obj->key()=>$objId]);
            }
        }

        if(r('isAdmin')){//机构端->管理老师
            $schoolId = r_int('schoolId');
            $schoolTeacher = new SchoolTeacher();
            $schoolTeacher->schoolId = $schoolId;
            $schoolTeacher->teacherId = r_int('teacherId');
            $findTeacher  = $schoolTeacher->find();
            if($findTeacher){
                $schoolTeacher->status   = r_int('status');
                $schoolTeacher->save();

                if($schoolTeacher->status == STATUS_PUBLISH){//抢了一个老师
                    if($obj->teacherId){
                        $obj->status = STATUS_PUBLISH;
                        $obj->schoolId = $schoolId;
                        $obj->save();
                    }
                }


                if(s('adminStatus')){
                    $obj->find($teacherId);
                    $schoolAdmin = new SchoolAdmin();
                    $schoolAdmin->schoolId = $schoolId;
                    $schoolAdmin->uid = $obj->uid;
                    $schoolAdmin->find();
                    $schoolAdmin->status = r('adminStatus');
                    $schoolAdmin->save();
                }
            }
        }else{//添加老师
            $obj->load();
            if($obj->status != STATUS_PUBLISH && !s('status')) $obj->status = STATUS_SUBMIT;//增加已经通过审核的直发
            $province   = $obj->hometown[0];
            $obj->homeProvinceId = $this->getProvinceId($province);
            $city       = $obj->hometown[1];
            $obj->homeCityId     = $this->getCityId($obj->homeProvinceId,$city);

            if(r('teacherAdminUid')){//教师管理端保存老师
                if($uid == r('teacherAdminUid')){
                    $obj->teacherAdminUid = r_int('teacherAdminUid');
                }
            }


            $obj->uid = $uid;
            $obj->ip  = myrequest::getIP();
            $obj->created = date('Y-m-d H:i:s');

            if($obj->teacherImgId){
                $img = new ImageFile();
                $img->find($obj->teacherImgId);
                $obj->uploadImg = $img->uploadImg;
            }

            $school = new School();
            $school->find($obj->schoolId);
            $obj->lat = $school->lat;
            $obj->lng = $school->lng;
            $obj->geo = $school->geo;
            if(s('years')){//教龄
                $obj->teacherYear = $obj->years;
            }


            $obj->save();

            $obj->hide();

            //保存教育经历
            $this->saveEdu($obj->teacherId);
            $this->saveJob($obj->teacherId);
            $this->saveImage($obj->teacherId);

            //增加老師
            $schoolId = r_int('schoolId');
            $schoolTeacher = new SchoolTeacher();
            $schoolTeacher->schoolId = $schoolId;
            $schoolTeacher->teacherId = $obj->teacherId;
            $schoolTeacher->status = STATUS_SUBMIT;
            $schoolTeacher->save();

            //教师标签
            $obj->arr['teacherLabel'] = $this->saveLabel($obj->teacherId);

        }
        $this->j(0,$obj->uploadImg,$obj->arr);
    }

    //找到省份的id
    private function getProvinceId($province){
        $provinceObj = new Province();
        $provinceObj->provinceName = $province;
        $find = $provinceObj->find();
        if(!$find){
            $provinceObj->status = STATUS_SUBMIT;
            $provinceObj->save();
        }

        return $provinceObj->provinceId;
    }

    //找到城市的id
    private function getCityId($provinceId,$city){
        $cityObj = new City();
        $cityObj->provinceId = $provinceId;
        $cityObj->cityName = $city;
        $find = $cityObj->find();
        if(!$find){
            $cityObj->status = STATUS_SUBMIT;
            $cityObj->save();
        }

        return $cityObj->cityIdOk;
    }

    //保存标签
    private function saveLabel($teacherId){
        if(!s('teacherLabelList')) return;
        $allImg = r('teacherLabelList');
        $rect = [];
        //删除之前的
        $teacherImage = new TeacherLabel();
        $sql = "DELETE FROM " . $teacherImage->table() . " WHERE teacherId=" . $teacherId;
        $teacherImage->query($sql);

        //if (!is_array($allImg)) $allImg = [$allImg];
        $i = 0;
        foreach ($allImg as $tmpObj) {
            $i++;

            if (!$tmpObj->labelId) continue;
            $tmpLabel = new Label();
            $tmpLabel->find($tmpObj->labelId);


            $teacherImage = new TeacherLabel();
            $teacherImage->teacherId = $teacherId;
            $teacherImage->labelId = $tmpObj->labelId;
            $teacherImage->labelName = $tmpLabel->labelName;
            $teacherImage->labelImg = $tmpLabel->labelImg;
            $teacherImage->status = STATUS_PUBLISH;//自己人不用审核
            $teacherImage->save();
            $rect[] = $teacherImage->arr;
        }
        

        return $rect;
    }

    private function saveImage($teacherId)
    {
        if(!s('teacherImages')) return ;
        $allImg = r('teacherImages');
        //删除之前的
        $teacherImage = new TeacherImage();
        $sql = "DELETE FROM " . $teacherImage->table() . " WHERE teacherId=" . $teacherId;
        $teacherImage->query($sql);

        if (!is_array($allImg)) $allImg = [$allImg];
        $i = 0;
        foreach ($allImg as $imgId) {
            $i++;

            if (!$imgId) continue;

            $img = new ImageFile();
            $find = $img->find($imgId);

            $teacherImage = new TeacherImage();
            $teacherImage->teacherId = $teacherId;
            $teacherImage->imageFileId = $imgId;
            $teacherImage->img = $img->uploadImg;
            $teacherImage->sort = $i;
            $teacherImage->status = STATUS_PUBLISH;//自己人不用审核
            $teacherImage->save();
        }
    }

    public function saveJob($teacherId){
        if(!s('teacherJobList')) return ;
        $teacherJobList = r('teacherJobList');
        $sql = "DELETE FROM tbl_teacher_job WHERE teacherId=".$teacherId;
        $teacherJob = new TeacherJob();
        $teacherJob->query($sql);

        foreach($teacherJobList as $item){
            $teacherJob = new TeacherJob();
            $teacherJob->teacherId  = $teacherId;
            $teacherJob->schoolName = $item->schoolName;
            $teacherJob->occupy = $item->occupy;
            $teacherJob->summary = $item->summary;
            $teacherJob->achievement = $item->achievement;
            $teacherJob->startTime = $item->startTime;
            $teacherJob->endTime   = $item->endTime;

            //数据校验
            if(!$teacherJob->schoolName && !$teacherJob->startTime){
                continue;
            }
            $teacherJob->save();
        }
    }

    public function saveEdu($teacherId){
        if(!s('teacherEduList')) return;
        $teacherEduList = r('teacherEduList');
        $sql = "DELETE FROM tbl_teacher_edu WHERE teacherId=".$teacherId;
        $teacherEdu = new TeacherEdu();
        $teacherEdu->query($sql);

        foreach($teacherEduList as $item){
            $teacherEdu = new TeacherEdu();
            $teacherEdu->teacherId  = $teacherId;
            $teacherEdu->schoolName = $item->schoolName;
            $teacherEdu->major = $item->major;
            $teacherEdu->levelId = $item->levelId;
            $teacherEdu->startTime = $item->startTime;
            $teacherEdu->endTime   = $item->endTime;

            //数据校验
            if(!$teacherEdu->major && !$teacherEdu->schoolName){
                continue;
            }
            $teacherEdu->save();
        }
        
    }


    //全部的列表
    public function allAction(){
        $uid = mylogin::getUid(true);

        $lat = mygeo::getLat($uid);
        $lng = mygeo::getLng($uid);


        $obj = new Teacher();
        $obj->load();
        $obj->status = STATUS_PUBLISH;
        $con = $obj->getConByLoad();
        if(r('keyword')){
            $key = addslashes(trim(r('keyword')));
            //$con .= " AND (teacherName LIKE '%$key%' OR summary LIKE '%$key%') ";
            $con .= " AND teacherName LIKE '%$key%'  ";
        }

        $sql = "SELECT * FROM ".$obj->table()." WHERE ".$con;
        switch(r('orderBy')){
            case "effect":
                $sql .= "ORDER BY effectScore DESC";
                break;
            case "service":
                $sql .= "ORDER BY serviceScore DESC";
                break;
            case "distance"://zhaopeixunapi.hkbao.com/school,all?orderBy=distance&lat=39.908491&lng=116.374328
                $sql .= "ORDER BY ".mygeo::getOrderBy();
                break;
            case "remark":
            default:
                $sql .= "ORDER BY finalScore DESC";
        }


        $obj->autoHide = false;
        $all = $obj->pager($sql);

        $startLat = s('lat')?r('lat'):-1;
        $startLng = s('lng')?r('lng'):-1;

        if($startLat==-1 || $startLng==-1){
            $user = new User();
            $user->find($uid);
            $startLat = $user->lat;
            $startLng = $user->lng;
        }

        $i = 0;
        foreach($all['list'] as $item){
            $distance = mygeo::getDistance($startLat,$startLng,$item['lat'],$item['lng']);
            $all['list'][$i] = $obj->hide($item);
            $all['list'][$i]['distance'] = $distance;
            $all['list'][$i]['uploadImg'] = $this->getSmallImg($item['uploadImg']);
            if($all['list'][$i]['teacherYear']){
                $all['list'][$i]['years'] = $all['list'][$i]['teacherYear'];
            }
            $i++;
        }

        $all['city'] = mygeo::getCity();
        $all['district'] = mygeo::getDistrictByCity($all['city'] );


        $i = 0;
        foreach($all['list'] as $row){
            $objId = $row[$obj->key()];
            $tmpImgObj = new TeacherLabel();
            $tmpImgObj->teacherId = $objId;
            $allImg = $tmpImgObj->all($tmpImgObj->getConByLoad());

            $all['list'][$i]['teacherLabel'] = $allImg;
            $i++;
        }

        $this->j(0, "list",$all);
    }

    private function getSmallImg($img){
        //https://img.myclhc.com/images/03aeba9e71501863aa70c6fe9c1da145.jpg
        //https://img.myclhc.com/images/90/03aeba9e71501863aa70c6fe9c1da145.jpg
        return preg_replace("/images\//","images/90/",$img);
    }

    private function isSchoolAdmin($uid,$schoolId){
        $schoolAdmin = new SchoolAdmin();
        $schoolAdmin->schoolId = $schoolId;
        $schoolAdmin->uid = $uid;
        $schoolAdmin->status = STATUS_PUBLISH;
       return $schoolAdmin->find();
    }


    public function summaryAction(){
        $uid = mylogin::getUid(true);
        $schoolId =  r_int('schoolId');
        $isSchoolAdmin  = $this->isSchoolAdmin($uid,$schoolId);
        if(!$isSchoolAdmin){
            $this->j(-1,'您不是这个机构的机构管理员',['schoolId'=>$schoolId]);
        }

        $schoolTeacher = new SchoolTeacher();
        $sql = "SELECT * FROM ".$schoolTeacher->table()." WHERE schoolId=".$schoolId;
        $all = $schoolTeacher->query($sql);
        $tmpTeacherIds = [-1];
        foreach($all as $item){
            $tmpTeacherIds[] = $item['teacherId'];
        }

        //找到合法的teacherId
        $sql = "SELECT teacherId FROM tbl_teacher WHERE  teacherId IN (".join(",",$tmpTeacherIds).") AND teacherName IS NOT NULL  AND status in (0,3,5)";
        $all = $schoolTeacher->query($sql);
        $tmpTeacherIds = [-1];
        foreach($all as $item){
            $tmpTeacherIds[] = $item['teacherId'];
        }

        //统计信息
        $sql = "SELECT COUNT(1) AS statusCount,st.status statusSummary FROM tbl_school_teacher st WHERE st.teacherId IN  (".join(",",$tmpTeacherIds).")  AND st.schoolId=$schoolId GROUP BY st.status ";
        $summary = $schoolTeacher->query($sql);
        $this->j(0,'',$summary);
    }


    //我的教师列表
    public function listAction() {
        $uid = mylogin::getUid(true);
        $schoolId =  r_int('schoolId');
        $isSchoolAdmin  = $this->isSchoolAdmin($uid,$schoolId);

        $schoolTeacher = new SchoolTeacher();
        $sql = "SELECT * FROM ".$schoolTeacher->table()." WHERE schoolId=".$schoolId;
        if($isSchoolAdmin && s('status')){
            $sql .= " AND status=".r_int('status');
        }

        $all = $schoolTeacher->query($sql);
        $allTeacherIds = [-1];
        foreach($all as $item){
            $allTeacherIds[] = $item['teacherId'];
        }

        //找到合法的teacherId
        $sql = "SELECT teacherId FROM tbl_teacher WHERE  teacherId IN (".join(",",$allTeacherIds).") AND teacherName IS NOT NULL  AND status in (0,3,4,5)";
        $all = $schoolTeacher->query($sql);
        $allTeacherIds = [-1];
        foreach($all as $item){
            $allTeacherIds[] = $item['teacherId'];
        }



        $obj = new Teacher();
        $mine = "";
        if(r('isAdmin')){//機構管理端
            if($isSchoolAdmin) {
                //if(s('status')) $obj->status = r_int('status');
            }else{
                $obj->status = STATUS_PUBLISH;
            }
        }else{//推廣員端
             $mine = " AND ( status=".STATUS_PUBLISH." OR uid=$uid) ";
        }

        $con = $obj->getConByLoad();
        if($con){
            $con .= " AND ";
        }else{
            $con = " status IN (0,3,4,5)  AND ";
        }
        $con .= "  teacherId IN (".join(",",$allTeacherIds).") AND teacherName IS NOT NULL ".$mine;
        $all = $obj->all($con);
        $i=0;
        foreach($all as $item){
            $teacherId = $item['teacherId'];
            if($teacherId){
                $teacherLabel = new TeacherLabel();
                $allLabel = $teacherLabel->all(['teacherId',$teacherId]);
                $all[$i]['teacherLabel'] = $allLabel;


                $teacherEdu = new TeacherEdu();
                $allLabel = $teacherEdu->all(['teacherId',$teacherId]);
                $all[$i]['teacherEdu'] = $allLabel;

                $courserSub = new CourseSub();
                $courserSub->find($item['courseSub']);
                $all[$i]['courseName'] = $courserSub->courseSub;

            }
            $i++;
        }

        $info = "";
        if(IS_DEBUG) $info=$con;

        $this->j(0,$info,$all);
    }

    public function likeListAction(){
        $uid = mylogin::getUid(false);
        $order = new Order();
        $order->orderType = ORDER_TYPE_LIKE;
        $order->teacherId = r_int('teacherId');
        $con = $order->getConByLoad();
        $con .= " AND buyerPay>0 ";
        $sql = "SELECT buyerUid FROM ".$order->table()." WHERE ".$con;
        $all = $order->pager($sql);
        $i = 0;
        foreach($all['list'] as $item){
            $all['list'][$i]['avatar'] = $this->getAvatarByUid($all['list'][$i]['buyerUid']);
            $i++;
        }

        $all['teacherId'] = r_int('teacherId');
        $this->j(0,"",$all);
    }

    private function getAvatarByUid($uid){
        $user = new User();
        $user->find($uid);
        if(preg_match("/^http/i",$user->avatar)){
            return $user->avatar;
        }else{
            return FRONT_URL.$user->avatar;
        }
    }


    //点赞
    public function likeAction(){
        $uid = mylogin::getUid(true);
        $obj = new TeacherLike();
        $obj->load();
        $teacherId = $obj->teacherId;
        $obj->uid = $uid;
        $find = $obj->find();

        //删除@todo 修改为状态模式,避免刷积分
        if($find){
            $sql = "DELETE FROM ".$obj->table()." WHERE teacherId=".$teacherId." AND uid=".$uid;
            $obj->query($sql);
        }else{ //保存
            $user = new User();
            $user->find($uid);

            $obj->avatar = $user->avatar;
            $obj->uid = $uid;
            $obj->ip = myrequest::getIP();
            $obj->created = date('Y-m-d H:i:s');
            $obj->save();

            $user->sendLike = $user->sendLike+1;
            $user->save();

            $teacher = new Teacher();
            $teacher->find($teacherId);
            $urlDesc = $teacher->teacherName;
            $url = "pages/teacherdetail/index?teacherId=$teacherId";
            $img = $teacher->uploadImg;
            ScoreExt::add($uid,1,5,"喜欢",$urlDesc,$url,$img);
        }

        //统计
        $sql = "SELECT COUNT(1) AS NUM FROM ".$obj->table()." WHERE teacherId=".$teacherId;
        $one = $obj->one($sql);
        $likeCount = $one['NUM'];

        //update
//        $obj = new Teacher();
//        $obj->likeCount = $likeCount;
//        $con = ['teacherId',$teacherId];
//        $obj->save($con);

        $this->j(0,'',['likeCount'=>$likeCount]);
    }

    //关注
    public function focusAction(){
        $uid = mylogin::getUid(true);
        $obj = new TeacherFocus();
        $obj->load();
        $teacherId = $obj->teacherId;
        $obj->uid = $uid;
        $find = $obj->find();

        //删除@todo 改为状态模式，避免刷积分
        if($find){
            $sql = "DELETE FROM ".$obj->table()." WHERE teacherId=".$teacherId." AND uid=".$uid;
            $obj->query($sql);
        }else{ //保存
            $obj->uid = $uid;
            $obj->ip = myrequest::getIP();
            $obj->created = date('Y-m-d H:i:s');
            $obj->save();

            $teacher = new Teacher();
            $teacher->find($teacherId);
            $urlDesc = $teacher->teacherName;
            $url = "pages/teacherdetail/index?teacherId=$teacherId";
            $img = $teacher->uploadImg;
            ScoreExt::add($uid,1,5,"关注",$urlDesc,$url,$img);
        }

        //统计
        $sql = "SELECT COUNT(1) AS NUM FROM ".$obj->table()." WHERE teacherId=".$teacherId;
        $one = $obj->one($sql);
        $likeCount = $one['NUM'];

        //update
        $obj = new Teacher();
        $obj->focusCount = $likeCount;
        $con = ['teacherId',$teacherId];
        $obj->save($con);

        $this->j(0,'',['focusCount'=>$likeCount]);
    }

    //想学
    public function wantAction(){
        $uid = mylogin::getUid(true);
        $teacherId = r_int('teacherId');
        $teacher = new Teacher();
        $find = $teacher->find($teacherId);
        if(!$find) $this->j(-1,"参数错误",['teacherId'=>$teacherId]);

        $obj = new TeacherWant();
        $obj->uid = $uid;
        $obj->teacherId= $teacherId;
        $find = $obj->find();
        if($find){//cancel
            /*$sql = "DELETE FROM ".$obj->table()." WHERE uid=$uid AND teacherId=$teacherId";
            $obj->query($sql);
            $teacher->want = $teacher->want-1;
            $teacher->save();*/
        }else{
            $obj->save();
            $teacher->want = $teacher->want+1 ;
            $teacher->save();
        }
        $this->j(0,"",['want'=>$teacher->want]);
    }

    //想学的人列表
    public function wantListAction(){
        $uid = mylogin::getUid(true);

        //当前的老师
        $teacher = new Teacher();
        $teacher->find(['uid'=>$uid]);

        $obj = new TeacherWant();
        $sql = "SELECT w.*,u.nick,u.mobile,u.avatar FROM ".$obj->table()." w LEFT JOIN  tbl_user u ON w.uid=u.uid WHERE w.teacherId=".intval($teacher->teacherId)."  ORDER BY ".$obj->key()." DESC ";
        $all = $obj->query($sql);
        $i =0;
        foreach($all as $item){
            if(!preg_match("/^http/i",$item['avatar'])){
                $all[$i]['avatar']  = FRONT_URL.$item['avatar'];
            }
            $i++;
        }

        $this->j(0,"",$all);
    }


    //学过的人列表
    public function learnedListAction(){
        $uid = mylogin::getUid(true);
        $id = r_int("teacherId");

        $this->j(0,'',$this->getTeacherLearned($id));
    }

    //学过
    public function learnedAction(){
        $uid = mylogin::getUid(true);
        $teacherId = r_int('teacherId');
        $teacher = new Teacher();
        $find = $teacher->find($teacherId);
        if(!$find) $this->j(-1,"参数错误",['teacherId'=>$teacherId]);

        $obj = new TeacherLearned();
        $obj->uid = $uid;
        $obj->teacherId= $teacherId;
        $find = $obj->find();
        if($find){//cancel
            /*$sql = "DELETE FROM ".$obj->table()." WHERE uid=$uid AND teacherId=$teacherId";
            $obj->query($sql);
            $teacher->learned = $teacher->learned-1;
            $teacher->save();*/
        }

        $user = new User();
        $user->find($uid);
        if($user->avatar){
            $obj->avatar = $user->avatar;
        }else{
            $obj->avatar = "/default.png";
        }
        if($user->nick){
            $obj->nick = $user->nick;
        }else{
            $obj->nick = "匿名";
        }

        $obj->save();
        $teacher->learned = $teacher->learned+1;
        $teacher->save();

        $this->j(0,"",['learned'=>$teacher->learned]);
    }

}



